<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 最长快乐前缀 -->
    <script>
      var longestPrefix = function (s) {
        let len = s.length
        let j = -1 // 前缀表统一减1
        let next = [j]
        for (let i = 1; i < len; i++) {
          while (j >= 0 && s[i] !== s[j + 1]) {
            j = next[j]
          }
          if (s[i] === s[j + 1]) j++
          next.push(j)
        }
        return s.substring(0, next[next.length - 1] + 1)
      }
      console.log(longestPrefix('level'))
    </script>
  </body>
</html>
